package io.gitee.horizon007.webspider.transformer;

import io.gitee.horizon007.webspider.WebSpider;
import io.gitee.horizon007.webspider.annotation.Context;
import io.gitee.horizon007.webspider.metadata.MetadataUtils;
import io.gitee.horizon007.webspider.metadata.PropertyMetadata;
import org.apache.commons.collections4.CollectionUtils;
import org.jsoup.select.Elements;

import java.util.List;

public class DeepTransformer implements ValueTransformer {

    @Override
    public boolean isAsync() {
        return true;
    }

    @Override
    public Object transform(WebSpider webSpider, Elements elements, Object instance, PropertyMetadata propertyMetadata, Context annotation) throws Throwable {
        List<? extends Class<?>> genericParameterList = propertyMetadata.getGenericParameterList();
        if (CollectionUtils.isEmpty(genericParameterList)) {
            throw new Exception(String.format(
                    "When using %s, only data type List<String>/String[]/String is supported, and the error is: '%s#%s'",
                    getClass().getSimpleName(),
                    propertyMetadata.getOwner().getType().getName(),
                    propertyMetadata.getName()
            ));
        }
        return webSpider.doFill(elements, MetadataUtils.metadata(propertyMetadata.getGenericParameterList().get(0)));
    }
}
